let Vue = null;
function install(_Vue){
  // console.log(_Vue)
  Vue = _Vue;
  Vue.mixin({
    beforeCreate() {
      console.log('beforeCreate')
      console.log(this)
      if(this.$options.store){
        // 证明这个是那个根实例
        this.$store = this.$options.store;
      }else if(this.$parent){
        // 若有$paren属性 证明这个组件是跟组件的后代组件
        this.$store = this.$parent.$store;
      }
    },
  })

}
class Store {
  constructor(options){
    // this.state = options.state // 没有响应式
    let vm = new Vue({
      data:{
        state:options.state
      }
    })
    this.state = vm.state;
    this.mutations = {};
    let mutations = options.mutations || {};
    Object.keys(mutations).forEach(key=>{
      // key 就是传进来的mutations中的属性名
      this.mutations[key] = (option)=>{
        mutations[key].call(this,this.state,option)
      }
    })


    this.actions = {};
    let actions = options.actions || {};
    Object.keys(actions).forEach(key=>{
      //key actions中的每一个属性名
      this.actions[key] = (option)=>{
        actions[key].call(this,this, option)
      }
    })



    this.getters = {};
    let getters = options.getters || {};
    Object.keys(getters).forEach(key=>{
      Object.defineProperty(this.getters,key,{
        get:()=>{
          return getters[key].call(this,this.state)
        }
      })
    })

    this.commit = (type,option)=>{
      this.mutations[type](option)
    }
  }
  // commit(type,option){
  //   // 要执行mutations中函数
  //   this.mutations[type](option)
  // }
  dispatch(type,option){
    this.actions[type](option)
  }
}
// mapState mapMutations  mapGetters mapActions

export function mapState(ary=[]){
  let obj = {};
  // obj = {
  //   count(){
  //     return this.$store.state.count
  //   }
  // }
  ary.forEach(key=>{
    obj[key] = function(){
      return this.$store.state.count
    }
  })
  return obj;
}

export function mapMutations(ary){
  let obj = {};
  ary.forEach(key=>{
    obj[key] = function(option){
      return this.$store.commit(key,option)
    }
  })

  return obj
}

export default {
  install,
  Store
}